import { reqMenus, saveOrUpdate, deleteMenu, getEditMenuInfo } from '@/api/menus'
import type { MenuItem, CreateOrEditMenu } from '@/api/menus'
import router from '@/router'

export function useMenus() {
  // const allMenus = ref<MenuItem[]>() // 会提示 MenuItem[] || undefined
  const allMenus = ref([] as MenuItem[])

  // 新建和编辑状态
  const isCreate = ref(true)
  const msgCreate = computed(() => (isCreate.value ? '创建菜单' : '更新菜单'))

  // 获取所有菜单
  const getAllMenus = async () => {
    const { data } = await reqMenus()
    // console.log(data.data)
    if (data.code === '000000') {
      allMenus.value = data.data
    } else {
      ElMessage.error('获取菜单信息失败')
      throw new Error('获取菜单信息失败')
    }
  }

  // 过滤出一级菜单
  const topMenus = computed(() => allMenus.value.filter((menu) => menu.level === 0))

  // 表单数据
  const formData = ref<CreateOrEditMenu>({
    description: '',
    href: '',
    icon: '',
    name: '',
    orderNum: 0,
    parentId: -1,
    shown: true
  })

  // 菜单添加或编辑表单提交事件
  const onSubmit = async () => {
    const { data } = await saveOrUpdate(formData.value)
    if (data.code === '000000' && data.data) {
      ElMessage.success(`${msgCreate.value}成功！`)
      router.push('/menus')
    } else {
      ElMessage.error(`${msgCreate.value}失败`)
      throw new Error(`${msgCreate.value}失败`)
    }
  }

  // 删除菜单
  const handleDelete = async (id: string) => {
    console.log(id)
    await ElMessageBox.confirm('确认要删除该菜单吗？', '删除提示').catch(() => {
      ElMessage.info('删除菜单已取消')
      return new Promise(() => {})
    })

    const { data } = await deleteMenu(id)
    if (data.code === '000000' && data.data) {
      ElMessage.success('菜单删除成功！')
      getAllMenus()
    } else {
      ElMessage.error('删除菜单失败')
      throw new Error('删除菜单失败')
    }
  }

  // 根据id获取菜单信息给编辑
  const getMenuInfoById = async (id: string) => {
    if (Number(id)) {
      isCreate.value = false
    } else {
      isCreate.value = true
      return
    }
    const { data } = await getEditMenuInfo(id)
    if (data.code === '000000') {
      formData.value = data.data.menuInfo
    } else {
      ElMessage.error('获取编辑菜单失败')
      throw new Error('获取编辑菜单失败')
    }
  }

  return { allMenus, topMenus, formData, getAllMenus, onSubmit, handleDelete, getMenuInfoById, msgCreate }
}
